package com.flyzing.genl.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import com.flyzing.genl.GenLight;


/**
 * @author yaoguangyao
 * @Date 2020年12月30日
 */
public class TemplateHelper {
	private static final TemplateHelper INSTANCE = new TemplateHelper();

	private static TemplateEngine templateEngine;
	
	private TemplateHelper() {
		init();
	}
	
	public static TemplateHelper getInstance() {
		return INSTANCE;
	}
	
	/**
	 * 初始化
	 */
	public static void init() {
		StringTemplateResolver templateResolver = new StringTemplateResolver();
		templateResolver.setTemplateMode("TEXT");
//		URL url = GenLight.class.getClassLoader().getResource("templates"); 
//		templateResolver.setPrefix(url.getPath() + "/");
//		templateResolver.setSuffix(".tpl");
		templateEngine = new TemplateEngine();
		templateEngine.setTemplateResolver(templateResolver);
	}
	
	/**
	 * 生成文件
	 * @param templateName
	 * @param path
	 * @param data
	 */
	public void process(String templateName, String path, Object data) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(path));
			Context context = new Context();
			context.setVariable("data", data);
			String content = readFile(templateName);
			templateEngine.process(content, context, out);
		} catch (IOException e) {
			throw new RuntimeException(path + "生成失败", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private String readFile(String templateName) {
		StringBuffer sb = new StringBuffer();
		InputStream is = GenLight.class.getResourceAsStream("/templates/" + templateName + ".tpl");
		BufferedReader br = null;
		String line = "";
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while((line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
}
